package Main;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URL;
import java.util.Scanner;

public class Main {
    public static void main(String[] args){
        System.out.println("blibli专栏图片下载器");
        // 获得要保存的位置和目标网址
        Scanner sc = new Scanner(System.in);

        System.out.println("请输入目标网址：");
        String url = sc.next();

        System.out.println("请输入要存储在什么盘符(如：D / C / E 等)：");
        String pathName = sc.next().toUpperCase();

        // 记录程序运行时间
        long s = System.currentTimeMillis();

        // 开始下载
        JsoupUtil(url,pathName);

        // 输出程序共用时多长时间
        long e = System.currentTimeMillis();
        System.out.println("下载图片用时：" + (e-s) + "毫秒");
        System.out.println("按回车键退出");
        Enter();

    }

    public static void JsoupUtil(String src,String pathName){
        FileOutputStream outputStream = null;
        InputStream inputStream = null;

        try {
            Document document = Jsoup.parse(new URL(src),10000);
            Elements documentClass = document.select(".article-holder figure img");
            int id = 1;
            for (Element aClass : documentClass) {
                String imageSrc = aClass.attr("data-src");
                inputStream = new URL("https:" + imageSrc).openConnection().getInputStream();

                File file = new File(pathName + ":\\blibliImages");
                file.mkdirs();
                File newFile = new File(file,id + ".jpg");
                newFile.createNewFile();
                outputStream = new FileOutputStream(newFile);

                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = inputStream.read(bytes)) != -1){
                    outputStream.write(bytes, 0 ,len);
                }
                System.out.println(id + ".jpg下载完毕");
                id++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    public static void Enter(){
        try {
            new BufferedReader(new InputStreamReader(System.in)).readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
